<template>
	<coreshop-page title="设置密码" mode="left">
		<view class="layout-password-box">
			<view class="password-box">
				<view class="item-box" v-if="state.oldpassWord">
					<view class="lab">旧密码</view>
					<view class="val">
						<uv-input placeholder="请输入旧密码" :password="true" border="surround"
							v-model="state.pwd"></uv-input>
					</view>
				</view>
				<view class="item-box">
					<view class="lab">新密码</view>
					<view class="val">
						<uv-input placeholder="请输入新密码" :password="true" border="surround"
							v-model="state.newPwd"></uv-input>
					</view>
				</view>
				<view class="item-box">
					<view class="lab">确认密码</view>
					<view class="val">
						<uv-input placeholder="请确认密码" :password="true" border="surround"
							v-model="state.rePwd"></uv-input>
					</view>
				</view>
			</view>

			<view class="save-box" @click="handleSubmit">保存</view>
		</view>
	</coreshop-page>
</template>
<script setup lang="ts">
	import { reactive } from 'vue';
	import { queryUserInfo, queryEditPwd } from '@/core/api';
	import type { Response, UserInfoType } from '@/core/models';
	import { onLoad } from '@dcloudio/uni-app';
	import { handleShowToast } from '@/core/utils';

	const state = reactive<{
		pwd : string;
		newPwd : string;
		rePwd : string;
		oldpassWord : boolean;
		submitStatus : boolean;
	}>({
		pwd: "",
		newPwd: "",
		rePwd: "",
		oldpassWord: true,
		submitStatus: true,
	})

	onLoad(() => {
		getUserInfo();
	});

	/** 获取用户信息 */
	const getUserInfo = async () => {
		const userInfo : Response<UserInfoType> = await queryUserInfo();
		state.oldpassWord = userInfo?.data?.passWord ? true : false;
	}

	/** 提交 */
	const handleSubmit = async () => {
		if (!state.submitStatus) {
			return;
		}
		if (state.oldpassWord && !state.pwd) {
			handleShowToast('请输入密码'); return;
		}
		if (!state.newPwd) {
			handleShowToast('请输入密码'); return;
		}
		if (!state.rePwd) {
			handleShowToast('请输入密码'); return;
		}
		if (state.rePwd != state.newPwd) {
			handleShowToast('两次输入的密码不相等'); return;
		}
		state.submitStatus = false;

		const pwdData : Response<any> = await queryEditPwd({
			pwd: state.pwd,
			newpwd: state.newPwd,
			repwd: state.rePwd
		});
		if (pwdData.status) {
			state.submitStatus = true;
			handleShowToast('修改成功', 'success', () => {
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					});
				}, 1500)
			});
		} else {
			state.submitStatus = true;
			handleShowToast('上传失败');
		}
	}
</script>
<style lang="scss" scoped>
	@import './password.scss';
</style>